package com.banciyuan.bcywebview.biz.detail.goods;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.fragment.BaseFragment;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.utils.download.DownLoadUtils;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.IoUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by hy on 2015/6/29.
 */
public class GoodsBigImageActivity extends BaseActivity {

    private List<Fragment> mList = new ArrayList<>();
    private ViewPager pager;
    private TextView tvPage;
    private TextView tvCheck;
    private TextView tvSave;
    private ArrayList<String> imageUrls;
    private TextView tv_load;
    private LinearLayout btn_container;
    private int index;
    private int totalPage;

    private static final int REQUEST_WRITE_EXTERNAL_STORAGE = 2132;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_newviewpicture);
        initArgs();
        initUi();
        initAction();
    }

    @Override
    protected void initArgs() {
        Intent intent = getIntent();
        imageUrls = intent.getStringArrayListExtra("imageUrls");
        index = intent.getIntExtra("position", 0);
    }

    @Override
    protected void initAction() {
        tvSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save();
            }
        });
    }

    @Override
    protected void initUi() {
        tv_load = (TextView) findViewById(R.id.tv_load);
        tvSave = (TextView) findViewById(R.id.tv_save);
        tvCheck = (TextView) findViewById(R.id.tv_check);
        btn_container = (LinearLayout) findViewById(R.id.btn_container);

        tvSave.setVisibility(View.VISIBLE);
        tv_load.setVisibility(View.GONE);
        btn_container.setVisibility(View.VISIBLE);
        tvCheck.setVisibility(View.GONE);

        pager = (ViewPager) findViewById(R.id.pager);
        tvPage = (TextView) findViewById(R.id.tv_page);
        for (int i = 0; i < imageUrls.size(); i++) {
            Fragment fragment = new PicShowFragment();
            Bundle bundle = new Bundle();
            bundle.putString("path", imageUrls.get(i));
            fragment.setArguments(bundle);
            mList.add(fragment);
        }
        pager.setAdapter(new MyAdapter(getSupportFragmentManager()));
        pager.addOnPageChangeListener(new MyOnPageListener());
        pager.setCurrentItem(index);
        totalPage = imageUrls.size();
        int newPosition = index + 1;
        tvPage.setText(newPosition + "/" + totalPage);
        tvPage.setVisibility(View.VISIBLE);
    }

    private void save() {
        if (ActivityCompat.checkSelfPermission(GoodsBigImageActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(GoodsBigImageActivity.this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                MyToast.show(GoodsBigImageActivity.this, getString(R.string.vailed_permission));
            } else {
                ActivityCompat.requestPermissions(GoodsBigImageActivity.this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        REQUEST_WRITE_EXTERNAL_STORAGE);
            }
        } else {
            ImageLoader.getInstance().loadImage(imageUrls.get(index), ImageOptions.optionsCopy, new SimpleImageLoadingListener() {
                @Override
                public void onDiskCacheComplete(String imageUri, File mfile, String type) {
                    setTask(mfile);
                }
            });
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        //判断请求码，确定当前申请的权限
        if (requestCode == REQUEST_WRITE_EXTERNAL_STORAGE) {
            //判断权限是否申请通过
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                ImageLoader.getInstance().loadImage(imageUrls.get(index), ImageOptions.optionsCopy, new SimpleImageLoadingListener() {
                    @Override
                    public void onDiskCacheComplete(String imageUri, File mfile, String type) {
                        setTask(mfile);
                    }
                });
            } else {
                MyToast.show(GoodsBigImageActivity.this, getString(R.string.operation_fail));
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


    private void setTask(File file) {
        new AsyncTask<File, Boolean, Boolean>() {
            @Override
            protected Boolean doInBackground(File... files) {
                boolean flag = false;
                try {
                    InputStream is = new FileInputStream(files[0]);
                    flag = DownLoadUtils.saveReal(imageUrls.get(index), is, new IoUtils.CopyListener() {
                        @Override
                        public boolean onBytesCopied(int current, int total) {
                            return true;
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                } catch (OutOfMemoryError e) {
                    e.printStackTrace();
                }
                return flag;
            }

            @Override
            protected void onPostExecute(Boolean aBoolean) {
                try {
                    if (aBoolean) {
                        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        Uri uri = Uri.fromFile(DownLoadUtils.getFile(imageUrls.get(index)));
                        intent.setData(uri);
                        sendBroadcast(intent);
                        MyToast.show(GoodsBigImageActivity.this, getString(R.string.pic_saved));
                    } else {
                        MyToast.show(GoodsBigImageActivity.this, getString(R.string.download_fail));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.execute(file);
    }

    private class MyOnPageListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            index = position;
            position = position + 1;
            tvPage.setText(position + "/" + totalPage);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    class MyAdapter extends FragmentPagerAdapter {

        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mList.get(position);
        }

        @Override
        public int getCount() {
            return mList.size();
        }
    }


    public static class PicShowFragment extends BaseFragment {

        private WebView mContentWv;
        private ProgressBar loading;
        private String path;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.picshow_layout, null);
            try {
                initArgs();
                initView(view);
                initAction();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return view;
        }

        @Override
        protected void initArgs() {
            path = getArguments().getString("path");
        }


        private void initView(View view) {
            mContentWv = (WebView) view.findViewById(R.id.picshow_content_wv);
            loading = (ProgressBar) view.findViewById(R.id.loading);
            loading.setVisibility(View.VISIBLE);
            mContentWv.setVisibility(View.INVISIBLE);
            mContentWv.setOverScrollMode(View.OVER_SCROLL_NEVER);
            mContentWv.setOnTouchListener(new LargeOnTouchListener(mContentWv));
            mContentWv.getSettings().setJavaScriptEnabled(false);
            mContentWv.getSettings().setUseWideViewPort(true);
            mContentWv.getSettings().setLoadWithOverviewMode(true);
            mContentWv.getSettings().setBuiltInZoomControls(true);
            mContentWv.getSettings().setDisplayZoomControls(false);
            mContentWv.getSettings().setSupportZoom(true);
            mContentWv.setVerticalScrollBarEnabled(false);
            mContentWv.setHorizontalScrollBarEnabled(false);
            mContentWv.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
//            mContentWv.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
            showContent(path);

        }


        private void showContent(String path) {
            StringBuilder str2 = new StringBuilder();
            str2.append("<html><head><style>html,body{background-color:#000;margin:0;padding:0;}*{-webkit-tap-highlight-color:rgba(0, 0, 0, 0);}</style></head>\n");
            str2.append("<body>\n");
            str2.append("<table style=\"background-color:#000;width: 100%;height:100%; border: 0; margin: 0; padding: 0; border-collapse: collapse; border-spacing: 0;\">\n");
            str2.append("<tr style=\"background-color:#000;width: 100%; border: 0; margin: 0; padding: 0;\">\n");
            str2.append("<td align=\"middle\" align=\"center\" style=\"background-color:#000;width: 100%; border: 0; margin: 0; padding: 0;\">\n");
            str2.append("<div style=\"display:block\">\n");
            str2.append("<img src=\"" + path + "\" width=\"100%\" style=\"background-color:#000;border: 0; display: block;\" />\n");
            str2.append("</div>\n");
            str2.append("</td>\n");
            str2.append("</tr>\n");
            str2.append("</table>\n");
            str2.append("</body></html>");
            mContentWv.setBackgroundColor(Color.TRANSPARENT);
            mContentWv.loadDataWithBaseURL("file:///android_asset/", str2.toString(), "text/html", "utf-8", null);
            loading.setVisibility(View.GONE);
            mContentWv.setVisibility(View.VISIBLE);
        }


        private class LargeOnTouchListener implements View.OnTouchListener {

            GestureDetector gestureDetector;

            public LargeOnTouchListener(final View view) {
                gestureDetector = new GestureDetector(view.getContext(),
                        new GestureDetector.SimpleOnGestureListener() {
                            @Override
                            public boolean onSingleTapConfirmed(MotionEvent e) {
                                getActivity().finish();
                                return true;
                            }
                        });
            }

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                gestureDetector.onTouchEvent(event);
                return false;
            }
        }
    }


}
